package org.jeecg.common.util;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class FileUtil {
    private static final int BUFFER_SIZE = 2*1024;


    public static void toZip(String srcDir, OutputStream out , HttpServletResponse response){
        ZipOutputStream zos= null;
        try{
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile,zos,sourceFile.getName(),true);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(zos != null){
                try {
                    zos.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    private static void compress(File sourceFile,ZipOutputStream zos,String name,boolean keepDirStructure) throws IOException {
        byte[] buf = new byte[BUFFER_SIZE];
        if(sourceFile.isFile()){
            zos.putNextEntry(new ZipEntry(name));
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1){
                zos.write(buf,0,len);
            }
            zos.closeEntry();
            in.close();
        }else{
            File[] listFiles = sourceFile.listFiles();
            if(listFiles == null || listFiles.length == 0){
                if(keepDirStructure){
                    zos.putNextEntry(new ZipEntry(name +"/"));
                    zos.closeEntry();
                }
            }else{
                for (File file :listFiles){
                    if(keepDirStructure){
                        compress(file,zos,name+"/"+file.getName(),keepDirStructure);
                    }else{
                        compress(file,zos, file.getName(),keepDirStructure);
                    }
                }
            }
        }
    }

    public static void uncompress(String zipFilePath,String destDirectory){
        File destDir = new File(destDirectory);
        if(!destDir.exists()){
            destDir.mkdir();
        }

        try {
            byte[] buffer = new byte[1024];
            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFilePath)));
            ZipEntry zipEntry;

            while ((zipEntry = zis.getNextEntry()) != null) {
                String entryName = zipEntry.getName();
                String filePath = destDirectory + File.separator + entryName;

                if (zipEntry.isDirectory()) {
                    File dir = new File(filePath);
                    dir.mkdirs();
                } else {
                    FileOutputStream fos = new FileOutputStream(filePath);
                    BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);

                    int len;
                    while ((len = zis.read(buffer)) > 0) {
                        bos.write(buffer, 0, len);
                    }

                    bos.flush();
                    bos.close();
                }

                zis.closeEntry();
            }

            zis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void dowloadFile(File file,HttpServletResponse response){
        OutputStream toClient =null;
        try{
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getAbsoluteFile()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(file.getName(),"UTF-8"));
            toClient.write(buffer);
            toClient.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(toClient != null){
                try {
                    toClient.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }


    public static void dowloadZip(File file,HttpServletResponse response){
        OutputStream toClient =null;
        try{
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getAbsoluteFile()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(file.getName(),"UTF-8"));
            toClient.write(buffer);
            toClient.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(toClient != null){
                try {
                    toClient.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    public static void copyFile(String orignFile,String destFile){
        try {
            // 创建输入流和输出流
            FileInputStream fis = new FileInputStream(orignFile);
            FileOutputStream fos = new FileOutputStream(destFile);
            // 创建缓冲区
            byte[] buffer = new byte[1024];
            int bytesRead;
            // 从输入流读取数据，并写入输出流
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            // 关闭流
            fis.close();
            fos.close();

            System.out.println("文件复制成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
